package com.sanri.tools.bigfileupload.storage;

import com.sanri.tools.bigfileupload.dtos.FileMeta;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
@Slf4j
public class LocalS3FileStorage implements FileStorage {
    /**
     * 上传的基准路径，默认取当前路径
     */
    @Value("${sanri.webui.upload.basePath:/tmp/}")
    private String basePath;

    @Override
    public void appendPart(String bucket, String fileId, byte[] part) throws IOException {
        File base = new File(basePath);
        File targetDir = new File(base, bucket);
        targetDir.mkdirs();

        File file = new File(targetDir, fileId);
        try(FileOutputStream fileOutputStream = new FileOutputStream(file, true)){
            IOUtils.write(part, fileOutputStream);
        }
    }

    @Override
    public FileMeta fileMeta(String bucket, String fileId) throws IOException {
        File base = new File(basePath);
        File targetDir = new File(base, bucket);
        targetDir.mkdirs();

        File file = new File(targetDir, fileId);
        if (file.exists()){
            final FileMeta fileMeta = new FileMeta();
            fileMeta.setFileName(file.getName());
            fileMeta.setFileSize(file.length());
            final byte[] bytes = FileUtils.readFileToByteArray(file);
            final String md5Hex = DigestUtils.md5Hex(bytes);
            fileMeta.setMd5(md5Hex);
            return fileMeta;
        }
        return null;
    }
}
